﻿using System;
using System.IO;

namespace CodeToHtml {
    public class BetterStringReader : TextReader {
        private readonly string _string;
        private readonly int _length;
        private int _position;

        public BetterStringReader(string str) {
            _string = str;
            _position = 0;
            _length = _string.Length;
        }

        public bool IsEndOfString() {
            return Peek() == -1;
        }

        public override int Peek() {
            if (_position == _length) {
                return -1;
            }
            return _string[_position];
        }

        public string Peek(int length) {
            if (_position + length > _length) {
                throw new IndexOutOfRangeException("Length specified is past the end of the string");
            }
            return _string.Substring(_position, length);
        }

        public string Read(int length) {
            string result = Peek(length);
            _position += length;
            return result;
        }

        public override int Read() {
            if (_position == _length) {
                return -1;
            }
            return _string[_position++];
        }

        public bool StartsWith(string str) {
            if (LeftToRead < str.Length) {
                return false;
            }
            string peekData = Peek(str.Length);
            return peekData == str;
        }

        public bool StartsWith(char ch) {
            if (LeftToRead < 1) {
                return false;
            }
            return (char)Peek() == ch;
        }

        public int LeftToRead {
            get { return _length - _position; }
        }

        public string RestOfString {
            get { return Peek(LeftToRead); }
        }
    }
}
